package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            // 等待客户端端建立连接
            Socket clientSocket = serverSocket.accept();
//            Thread t = new Thread(() -> {
//                ProcessConnection(clientSocket);
//            });
//            t.start();
            ExecutorService service = Executors.newCachedThreadPool();
            service.submit(() -> {
                ProcessConnection(clientSocket);
            });
        }
    }

    private void ProcessConnection(Socket clientSocket) {
        System.out.printf("[%s %d] 客户端上线！\n", clientSocket.getInetAddress(), clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner in = new Scanner(inputStream);
            PrintWriter out = new PrintWriter(outputStream);
            while(true){
                // 1. 等待客户端发送请求
                if(!in.hasNext()){
                    break;
                }
                String request = in.next();
                // 2. 根据请求计算响应
                String response = process(request);
                // 3. 返回响应
                out.println(response);
                out.flush();
                System.out.printf("[%s %d] request: %s response: %s\n",
                        clientSocket.getInetAddress(), clientSocket.getPort(), request, response);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                System.out.printf("[%s %d] 客户端下线！\n", clientSocket.getInetAddress(), clientSocket.getPort());
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
